package com.yanyuan.snio.part;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author: yanyuan
 * @Date: 2021/3/4 17:20
 * @Description:
 * 分散(scatter)与聚集(gather)
 * 1. 分散读取（scattering Reads):将通道的数据分散到多个缓冲区中
 * 2. 聚集写入（gathering writes）:将多个缓冲区的数据聚集到通道中
 */
@Slf4j
public class NioP5ScatterAndGather {
    
    //分散聚集
    public void scatterAndGather() throws IOException {
        RandomAccessFile randomAccessFile = new RandomAccessFile("Thinking in Java.txt", "rw");
        //1.获取通道
        FileChannel channel1 = randomAccessFile.getChannel();
        //2.分配指定大小缓存区
        ByteBuffer buf1k = ByteBuffer.allocate(1024);
        ByteBuffer buf5k = ByteBuffer.allocate(1024 * 5);
        //3.分散读取
        ByteBuffer[] bufs = {buf1k, buf5k};
        channel1.read(bufs);
        for (ByteBuffer buf: bufs) {
            buf.flip();
        }
        log.info("buf1k : {}", new String(bufs[0].array(), 0, bufs[0].limit()));
        log.info("buf5k : {}", new String(bufs[1].array(), 0, bufs[1].limit()));
    }
}
